/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * JustForMe.java
 *
 * Created on Nov 18, 2012, 1:41:38 PM
 */
package org.je.justforme.ui;

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;
import org.je.justforme.OfferManager;
import org.je.justforme.http.DefaultProperties;

/**
 *
 * @author jeddy
 */
public class JustForMe extends javax.swing.JDialog {

    private OfferManager offerMgr = null;

    private static class HttpResult {
        public enum ResultStatus {
            OK, ERROR;
        }
        String msg;
        ResultStatus status;
    }

    /** Creates new form JustForMe */
    public JustForMe(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        setTitle("Just for you, Just for me!");
        buttonAddAll.setEnabled(false);
        textDetails.setEditable(false);
        Properties props = DefaultProperties.getDefaultProps();
        textUname.setText(props.getProperty(DefaultProperties.PROP_UNAME));
        // this is CLEAR TEXT PASSWORD, maybe we should not save this!
        textPassword.setText(props.getProperty(DefaultProperties.PROP_PASSWORD));
        textDetails.setLineWrap(true);
        textDetails.append("Enter user information and click login. This application will add ALL offers from Vons/Pavillons justforyou program, rather then having to click 300+ offers");
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        textUname = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        textPassword = new javax.swing.JPasswordField();
        buttonLogin = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        textDetails = new javax.swing.JTextArea();
        buttonAddAll = new javax.swing.JButton();
        buttonClose = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel1.setText("Username: ");

        jLabel2.setText("Password:");

        buttonLogin.setText("Login");
        buttonLogin.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonLoginActionPerformed(evt);
            }
        });

        jPanel1.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));

        jLabel3.setText("Details:");

        textDetails.setColumns(20);
        textDetails.setRows(5);
        jScrollPane1.setViewportView(textDetails);

        buttonAddAll.setText("Add all Offers!");
        buttonAddAll.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonAddAllActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 427, Short.MAX_VALUE)
                    .addComponent(jLabel3)
                    .addComponent(buttonAddAll, javax.swing.GroupLayout.Alignment.TRAILING))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(buttonAddAll)
                .addContainerGap())
        );

        buttonClose.setText("Close");
        buttonClose.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonCloseActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(buttonClose, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(textUname, javax.swing.GroupLayout.PREFERRED_SIZE, 366, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(textPassword, javax.swing.GroupLayout.PREFERRED_SIZE, 142, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(buttonLogin, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(textUname, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(textPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(buttonLogin))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(buttonClose)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void buttonLoginActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonLoginActionPerformed
        offerMgr = new OfferManager();
        textDetails.setText("");
        final String uname = textUname.getText();
        final String password = new String(textPassword.getPassword());
        List<String> errors = new ArrayList<String>();
        if (uname.isEmpty()) {
            errors.add("Username must not be empty");
        }
        if (password.isEmpty()) {
            errors.add("Password must not be empty");
        }
        if (!errors.isEmpty()) {
            StringBuilder sb = new StringBuilder("Correct the following issues:\n");
            for (String error : errors) {
                sb.append("  ").append(error).append("\n");
            }

            JOptionPane.showMessageDialog(rootPane, sb.toString(), "Error with login information", JOptionPane.ERROR_MESSAGE);
        } else {
            textDetails.append("Trying to login and get deals... ");
            SwingWorker<HttpResult, Object> sw = new SwingWorker<HttpResult, Object>() {

                @Override
                protected HttpResult doInBackground() throws Exception {
                    HttpResult res = new HttpResult();
                    res.status = HttpResult.ResultStatus.OK;
                    res.msg = "Login OK.";
                    try {
                        offerMgr.login(uname, password);
                        offerMgr.getAllOffers();
                    } catch (Exception e) {
                        res.status = HttpResult.ResultStatus.ERROR;
                        res.msg = "\n" + e.getMessage();
                        JOptionPane.showMessageDialog(rootPane, e.getMessage(), "Could not login!", JOptionPane.ERROR_MESSAGE);
                    }
                    return res;
                }

                @Override
                protected void done() {
                    try {
                        HttpResult res = get();
                        textDetails.append(res.msg);
                        textDetails.append("\n");
                        if (res.status == HttpResult.ResultStatus.OK) {
                            int offerCount = offerMgr.getNumberOfOffersNotSelected();
                            textDetails.append("Number of offers available : " + offerCount + "\n");
                            if (offerCount == 0){
                                textDetails.append("There are currently no offers to add at this time, check back later.");
                            } else {
                                buttonAddAll.setEnabled(true);
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            };
            sw.execute();

        }

    }//GEN-LAST:event_buttonLoginActionPerformed

    private void buttonCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonCloseActionPerformed
        DefaultProperties.saveSettings();
        System.exit(0);
    }//GEN-LAST:event_buttonCloseActionPerformed

    private void buttonAddAllActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonAddAllActionPerformed

        SwingWorker<HttpResult, Object> sw = new SwingWorker<HttpResult, Object>() {

            @Override
            protected HttpResult doInBackground() throws Exception {
                HttpResult res = new HttpResult();
                res.status = HttpResult.ResultStatus.OK;
                long s = System.currentTimeMillis();
                try {
                    int cnt = offerMgr.addAllOffers();
                    s = System.currentTimeMillis() - s;
                    res.msg = "Added " + cnt + " offers!\nDone in " + s + "ms.\nZING!";
                } catch (Exception e) {
                    res.status = HttpResult.ResultStatus.ERROR;
                    res.msg = e.getMessage();
                    JOptionPane.showMessageDialog(rootPane, e.getMessage(), "Could not add offers!", JOptionPane.ERROR_MESSAGE);
                }
                return res;
            }

            @Override
            protected void done() {
                try {
                    HttpResult res = get();
                    textDetails.append(res.msg);
                    textDetails.append("\n");
                    if (res.status == HttpResult.ResultStatus.OK) {
                        buttonAddAll.setEnabled(true);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        sw.execute();
        // TODO add your handling code here:
    }//GEN-LAST:event_buttonAddAllActionPerformed

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                JustForMe dialog = new JustForMe(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    public void windowClosing(java.awt.event.WindowEvent e) {
                        DefaultProperties.saveSettings();
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton buttonAddAll;
    private javax.swing.JButton buttonClose;
    private javax.swing.JButton buttonLogin;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea textDetails;
    private javax.swing.JPasswordField textPassword;
    private javax.swing.JTextField textUname;
    // End of variables declaration//GEN-END:variables
}
